package com.danbai.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.danbai.reggie.common.R;
import com.danbai.reggie.dto.DishDto;
import com.danbai.reggie.entity.Dish;
import com.danbai.reggie.entity.DishFlavor;
import com.danbai.reggie.mapper.DishMapper;
import com.danbai.reggie.service.DishFlavorService;
import com.danbai.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService{

    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 保存菜品表
     * @param dishDto
     */
    @Transactional
    public void saveWithFlavor(DishDto dishDto){
        //保存菜品的基本信息到菜品表
        //保存dish表中的数据
        this.save(dishDto);

        //菜品口味
        Long dishId = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();

        flavors.stream().map(item -> {
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());

        //保存菜品口味数据到菜品口味表
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 回显菜品数据
     * @param id
     * @return
     */
    public DishDto getByIdWithFlavor(@PathVariable Long id) {
        Dish dish = this.getById(id);

        //封装dish相关数据
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);

        //封装口味数据
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> dishFlavors = dishFlavorService.list(queryWrapper);

        dishDto.setFlavors(dishFlavors);

        return dishDto;
    }

    @Override
    public void updateByIdWithFlavor(DishDto dishDto) {
        //更新dish表
        this.updateById(dishDto);
        //根据id删除dishFlavor中的数据
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(queryWrapper);
        //根据id添加dishFlavor中的数据

        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map(item ->{
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        //批量添加
        dishFlavorService.saveBatch(flavors);

    }
}
